from selenium.webdriver.common.by import By
import time

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from web import DButils


class Mfund:
    def change(self, driver, username, password, paypwd, type1, type2):
        driver.find_element(By.ID, "username").send_keys(username)
        driver.find_element(By.ID, "password").send_keys(password)
        driver.find_element(By.ID, "login_btn").click()
        WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, "/html/body/div[1]/div/aside/div[2]/nav/ul/li[2]/a"))
        )
        driver.find_element(By.XPATH, "/html/body/div[1]/div/aside/div[2]/nav/ul/li[2]/a").click()
        WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.XPATH, "/html/body/div[1]/div/aside/div[2]/nav/ul/li[2]/ul/li[1]/a"))
        )
        time.sleep(1)
        driver.find_element(By.XPATH, "//a[contains(text(),'{}')]".format(type1)).click()
        driver.find_element(By.XPATH, "//button[@buybtnname='{}']".format(type2)).click()
        time.sleep(2)
        # 定位密码输入框
        password_input = driver.find_element(By.XPATH, "//div[@class='layui-layer-content']/input[@id='password']")
        # 直接通过 JavaScript 注入值
        driver.execute_script("arguments[0].value = '{}';".format(paypwd), password_input)
        driver.find_element(By.XPATH, "//*[@id='layui-layer1']/div[3]/a[1]").click()
        WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, "div.jconfirm-content"))
        )

    def change_result(self, driver, cardNum, username):
        text = driver.find_element(By.XPATH, "//div[@class='jconfirm-content']/div").text
        sql = "select balance from bankcard where cardNum=%s and userId=(select id from user where username=%s)"
        params = [cardNum, username]
        balance = int(DButils.select(sql, params)[0][0])
        result = [text, balance]
        return result

    def change_error_result(self, driver):
        text = driver.find_element(By.XPATH, "//div[@class='jconfirm-content']/div").text
        result = [text]
        return result
